﻿using System;
using System.Linq;

using HupunSDK.Core;
using HupunSDK.Common.Extend;
using System.Net.Http;
using System.Diagnostics;

namespace HupunSDK_API
{
    public class HupunApiClient : BaseClient, IBaseClient
    {
        private readonly HupunApiConfig config;

        private long timestamp;

        public HupunApiClient(HupunApiConfig config)
        {
            this.config = config;
        }

        public override string GetRequestUri(IRequest request)
        {
            timestamp = DateTime.Now.ToChinaTimeStamp();
            if (request.GetHttpMethod() == HttpMethod.Post)
            {
                return config.ApiUrl + request.GetApiName();
            }

            var dic = request.GetParameters().CleanupDictionary();
            dic.Add("_app", config.Key);
            dic.Add("_t", timestamp);
            dic.Add("_sign", GetSign(request));
            return config.ApiUrl + request.GetApiName() + "?" + dic.ToSortQueryParameters(true);
        }

        public override string GetRequestBody(IRequest request)
        {
            if (request.GetHttpMethod() == HttpMethod.Get)
            {
                return string.Empty;
            }

            var dic = request.GetParameters().CleanupDictionary();
            dic.Add("_app", config.Key);
            dic.Add("_t", timestamp);
            dic.Add("_s", "");
            dic.Add("_sign", GetSign(request));

            return dic.ToSortQueryParameters(true);
        }

        public override string GetSign(IRequest request)
        {
            var dic = request.GetParameters().CleanupDictionary();
            dic.Add("_app", config.Key);
            dic.Add("_t", timestamp);
            dic.Add("_s", "");

            var sortedParamsStr = dic.ToSortQueryParameters(true);
            return $"{config.Secret}{sortedParamsStr}{config.Secret}".GetMD5().ToUpper();
        }

        public override string MediaType => "application/x-www-form-urlencoded";

        public void ShowParams(IRequest request)
        {
            Trace.WriteLine($"uri: {GetRequestUri(request)}");
            Trace.WriteLine($"body: {GetRequestBody(request)}");
        }
    }
}
